import Footer from '@/components/Footer';
import RightContent from '@/components/RightContent';
import type {Settings as LayoutSettings} from '@ant-design/pro-layout';
import {PageLoading, SettingDrawer} from '@ant-design/pro-layout';
import {RunTimeLayoutConfig} from 'umi';
import {history} from 'umi';
import defaultSettings from '../config/defaultSettings';
import {currentUser as queryCurrentUser} from './services/ant-design-pro/api';
import {stringify} from 'querystring';
import {notification} from 'antd';
import {isNumber} from 'lodash';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
const whitePath = [
  loginPath,
  '/user/register',
  '/user/register-result',
  '/user/forget-password',
  '/user/forget-account',
];

// export const request: RequestConfig = {
//   errorConfig: {
//     adaptor: (resData) => {
//       return {
//         ...resData,
//         success: resData.ok,
//         errorMessage: resData.message,
//       };
//     },
//   },
// };

//拦截器-请求前拦截
function authHeaderInterceptor(url: any, options: any) {
  let headers = {TenantCode: 'e513f45c099239505054fead0a445fa2'};
  let token = localStorage.getItem('token');
  if (token) {
    // @ts-ignore
    headers.Authorization = `Bearer ${token}`;
  }
  options.headers = headers;
  return {options: options};
}

//拦截器-响应后拦截
const responseInterceptors = async (response: any, options: any) => {
  // console.log(options, response, "3")
  let content = response.headers.get('Content-Type');
  if (content && content.indexOf('application/json') >= 0) {
    const res = await response.clone().json(); //这里是关键，获取所有接口请求成功之后的数据
    // debugger;
    // console.log(res);
    if (res.code && res.code === 200) {
      res.success = true;
      res.status = 'ok';
      if (res.rows) {
        res.data = res.rows;
      }
      return res;
    } else if (res.code) {
      // console.log('3');
      const {search, pathname} = history.location;
      if (res.code == 401) {
        localStorage.removeItem('token');

        history.replace({
          pathname: loginPath,
          search: stringify({
            redirect: pathname + search,
          }),
        });
        // history.push(loginPath)
      }
      return {
        success: false,
        status: 'error',
        errorCode: res.code,
        showType: options.showType,
        errorMessage: res.msg,
      };
    }
  }

  return response;
};

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

// @ts-ignore
// @ts-ignore
/**
 * 异常处理程序
 */
// @ts-ignore
const errorHandler = (error: { response: Response }): Response => {
  const {response} = error;
  if (response && response.status && isNumber(response.status)) {
    const errorText = codeMessage[response.status] || response.statusText;
    // @ts-ignore
    const {status, url} = response;
    console.log(response, '3333333');
    // console.log(status)
    // 处理参数问题
    // let noParamUrl = url;
    // if (url.indexOf('?') !== -1) {
    //   noParamUrl = url.substring(0, url.indexOf('?'));
    // }

    // if (url.indexOf('/system/oauth/token') !== -1) {
    //   notification.error({
    //     message: `请求错误 [20002]: ${noParamUrl}`,
    //     description: '账号不存在或密码错误',
    //   });
    //   return response;
    // }
    if (status === 401) {
      notification.warn({
        message: '请重新登陆!',
      });
      // clearTokens();
      history.push(loginPath);
    } else {
      console.log(status);
      notification.error({
        message: `请求错误 [${status}]:`,
        description: errorText,
      });
    }
  } else if (!response) {
    notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常',
    });
  }
  return response;
};

export const request = {
  // errorHandler,
  // errorConfig: {
  //   adaptor: (resData: { code: number; msg: any; data: any; success: any }) => {
  //     // if (!resData.success) {
  //     //   if (resData.code === 200) {
  //     //     console.log({
  //     //       ...resData.data,
  //     //       success: true,
  //     //       status: 'ok',
  //     //     });
  //     console.log('222222222333222222');
  //     //     return {
  //     //       ...resData.data,
  //     //       success: true,
  //     //       status: 'ok',
  //     //     };
  //     //   } else {
  //     //     console.log('33333333333333333');
  //     //     return {
  //     //       success: false,
  //     //       errorCode: resData.code,
  //     //       // showType: 9,
  //     //       errorMessage: resData.msg,
  //     //     };
  //     //   }
  //     // }
  //     console.log(resData);
  //     console.log({
  //       ...resData,
  //       success: resData.code === 200,
  //       status: resData.code === 200 ? 'ok' : 'error',
  //       errorCode: resData.code,
  //       // showType: 9,
  //       errorMessage: resData.msg,
  //     });
  //     return resData;
  //
  //     // return {
  //     //   ...resData,
  //     //   success: resData.code === 200,
  //     //   status: resData.code === 200 ? 'ok' : 'error',
  //     //   errorCode: resData.code,
  //     //   // showType: 9,
  //     //   errorMessage: resData.msg,
  //     // };
  //   },
  // },
  // 新增自动添加AccessToken的请求前拦截器
  requestInterceptors: [authHeaderInterceptor],
  responseInterceptors: [responseInterceptors],
};

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading/>,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  console.log(history.location.pathname, whitePath.indexOf(history.location.pathname));
  // 如果是登录页面，不执行
  if (whitePath.indexOf(history.location.pathname) < 0) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
    };
  }
  return {
    fetchUserInfo,
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({initialState, setInitialState}) => {
  let company = initialState?.currentUser?.company;
  console.log(company);
  return {
    // menu: {
    //   // 每当 initialState?.currentUser?.userid 发生修改时重新执行 request
    //   params: initialState,
    //   request: async (params, defaultMenuData) => {
    //     // console.log(params, defaultMenuData)
    //     // defaultMenuData.concat(initialState.currentUser.menus);
    //     // console.log(defaultMenuData)
    //     return defaultMenuData
    //   },
    // },
    // menuDataRender: () => {
    //   return menu;
    // },
    title: '智慧安运安全管理系统',
    rightContentRender: () => <RightContent/>,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.company,
    },
    footerRender: () => <Footer/>,
    onPageChange: async () => {
      const {location} = history;
      let token = localStorage.getItem('token');
      if (token && location.pathname === loginPath) {
        const userInfo = await initialState?.fetchUserInfo?.();
        if (userInfo) {
          await setInitialState((s: any) => ({
            ...s,
            currentUser: userInfo,
          }));
          history.replace('/');
        }
      }
      // 如果没有登录，重定向到 login
      if (
        !initialState?.currentUser &&
        location.pathname !== loginPath &&
        whitePath.indexOf(location.pathname) < 0
      ) {
        history.push(loginPath);
      }
      // debugger;
      if (initialState?.currentUser &&
        (initialState?.currentUser.approve !== 2) &&
        location.pathname !== "/account/approve") {
        notification.warn({
          message: "账号未认证",
          description: '您的账号还没有认证,请先申请企业信息认证。如已申请,请等待认证通过!!',
        });
        history.push("/account/approve");
      }
    },
    links: isDev
      ? [
        // <Link to="/umi/plugin/openapi" target="_blank">
        //   <LinkOutlined/>
        //   <span>OpenAPI 文档3</span>
        // </Link>,
        // <Link to="/~docs">
        //   <BookOutlined/>
        //   <span>业务组件文档</span>
        // </Link>,
      ]
      : [],
    logo: 'https://gw.alipayobjects.com/mdn/rms_b5fcc5/afts/img/A*1NHAQYduQiQAAAAAAAAAAABkARQnAQ',
    // headerTitleRender: (logo, title, props) => {
    //   console.log(logo, title, props)
    //   return (
    //     <div
    //       id="customize_menu_header"
    //       style={{all: 'initial'}}
    //       // onClick={() => {
    //       //   window.open('https://remaxjs.org/');
    //       // }}
    //     >
    //       {logo}
    //       <span style={{display: 'inline-block', color: 'white'}}>
    //         <div>sd</div>
    //         <div>{title}</div>
    //       </span>
    //     </div>
    //   )
    // },
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && isDev && (
            <SettingDrawer
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState: any) => ({
                  ...preInitialState,
                  settings,
                })).then((r) => {
                });
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
